package core.compenent
{
	import core.RekooEvent;
	import core.RekooEventType;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.containers.VBox;
	import mx.controls.Button;
	import mx.effects.Move;
	import mx.events.EffectEvent;

	public class SubMenu extends VBox
	{
		private var RemoveStartEvent:String = "RemoveStartEvent";
		private var RemoveFinishEvent:String = "RemoveFinishEvent";
		private var AddStartEvent:String = "AddStartEvent";
		
		private var itemWidth:int = 158;
		private var itemHeight:int = 30;
		
		private var moveEffect:Move;
		private var cursor:int = -1;
		private var isAdd:Boolean = false;
		private var dataTemp:Object = null;
		private var lock:Boolean = false;
		
		private var currentSubMenu:String = "";
		
		public function SubMenu()
		{
			super();
			addEventListener(RemoveStartEvent,onRemoveStart);
			addEventListener(AddStartEvent,onAddStart);
			moveEffect = new Move();
			moveEffect.duration = 200;
			moveEffect.addEventListener(EffectEvent.EFFECT_END, onEffect);
		}
		
		override public function set data(value:Object):void
		{
			lock = true;
			if(cursor>=0)
			{
				dataTemp = value;
				isAdd = false;
				dispatchEvent(new Event(RemoveStartEvent));
			}
			else
			{
				lock = false;
				super.data=value;
				isAdd = true;
				dispatchEvent(new Event(AddStartEvent));
			}
		}
		
		private function onAddStart(e:Event):void
		{
			
			var item:Object = (data as Array)[cursor+1];
			if(item!=null)
			{
				var menu:Button = new Button();
				menu.styleName="subMenuButton";
				menu.label = item.label;
				menu.data = item;
				menu.addEventListener(MouseEvent.CLICK,onClick);
				addChild(menu);
				cursor++;
				moveEffect.xFrom = 0 - itemWidth;
				moveEffect.xTo =0;
				moveEffect.yTo = moveEffect.yFrom = cursor * itemHeight;
				moveEffect.target = menu;
				moveEffect.play();
			}
		}
		
		private function onRemoveStart(e:Event):void
		{
			if(cursor >= 0)
			{
				var menu:Button = getChildAt(cursor) as Button;
				menu.removeEventListener(MouseEvent.CLICK,onClick);
				moveEffect.xFrom = 0;
				moveEffect.xTo = itemWidth;
				moveEffect.yTo = moveEffect.yFrom = cursor * itemHeight;
				moveEffect.target = menu;
				moveEffect.play();
				
			}else{
				this.data = dataTemp;
			}
		}
		
		private function onEffect(e:EffectEvent):void
		{
			if(isAdd)
			{
				dispatchEvent(new Event(AddStartEvent));
			}
			else
			{
				var menu:Button = getChildAt(cursor) as Button;
				removeChild(menu);
				cursor--;
				dispatchEvent(new Event(RemoveStartEvent));
			}
		}
		
		private function onClick(e:MouseEvent):void
		{
			if(!lock && currentSubMenu != e.target.data.event){
				currentSubMenu = e.target.data.event;
				dispatchEvent(new RekooEvent(RekooEventType.MENU_ITEM_CLICK, e.target.data.event, true));
			}
		}
	}
}